#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time      :2022/6/1 15:16
# @Author    :cjw
from os.path import exists
from yaml import safe_load_all, safe_load, safe_dump


class FileBase:

	def __init__(self, file_path: str):
		if not exists(file_path):
			raise FileNotFoundError(f'找不到文件：{file_path}')
		self._file_path = file_path
		self._data = None


class YmlOperator(FileBase):
	"""yml文件操作"""

	def __init__(self, yml_path: str, multi: bool = False):
		"""
		:param yml_path: yml文件路径
		:param multi: 是否多节读取，yml文件通过'---'符号进行多节处理
		"""
		super(YmlOperator, self).__init__(yml_path)
		self._multi = multi

	@property
	def data(self):
		"""获取yml数据"""
		# 第一次获取数据时，才进行读取
		if not self._data:
			with open(self._file_path, encoding='utf-8') as f:
				if self._multi:
					self._data = list(safe_load_all(f))
				else:
					self._data = safe_load(f)
		return self._data

	def write(self, data):
		"""
		python数据写入到yml文件中
		:param data: python格式数据
		:return:
		"""
		with open(self._file_path, 'w', encoding='utf-8') as f:
			safe_dump(data, f)
